<?php

namespace app\common\controller;

use think\facade\Log;

trait JwtAuthorizedTrait
{
    /**
     * $payload Jwt 载荷，stdClass
     *
     * @var \stdClass
     */
    protected $payload;

    /**
     * Jwt 字符串
     *
     * @var string
     */
    protected $jwt;

    public function initialize()
    {
        parent::initialize();

        do {
            // 从header或query里面获取token
            $token = $this->request->header('Authorization');
            if (!$token) {
                $token = input('token');
                if (!$token) {
                    $this->payload = new \stdClass;
                    break;
                }
                $token = urldecode(urldecode($token));
            }

            $jwt = str_replace('Bearer ', '', $token);
            if (!$jwt) {
                $this->payload = new \stdClass;
                break;
            }
            // 解析jwt
            Log::debug("尝试解析Jwt: " . var_export($jwt, true));

            $this->payload = $this->decodeJwt($jwt);
            $this->jwt = $jwt;
        } while (0);

        // 调用用户自定义的初始化语句
        if (method_exists($this, 'init')) {
            $this->init();
        }
    }
}